package com.gitee.jmash.rbac.event;

import com.gitee.jmash.common.event.SafeEvent;
import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.rbac.RbacFactory;
import com.gitee.jmash.rbac.model.UserLogCreateReq;
import com.gitee.jmash.rbac.service.UserLogWrite;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.ObservesAsync;
import jakarta.enterprise.inject.spi.EventMetadata;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/** 安全事件日志处理. */
@ApplicationScoped
public class SafeEventDBLogHandle {

  private static Log log = LogFactory.getLog(SafeEventDBLogHandle.class);


  /** 异步安全日志. */
  public void handleAsyncEvent(@ObservesAsync SafeEvent event, EventMetadata metadata) {
    if (StringUtils.isBlank(event.getTenant())) {
      log.debug("---" + event + "---");
      return;
    }
    log.trace("---" + event.getTenant() + "---" + event.getEventType().name() + "---");
    UserLogWrite userLogWrite = null;
    try {
      userLogWrite = RbacFactory.getUserLogWrite(event.getTenant());
      UserLogCreateReq req = new UserLogCreateReq();
      req.setLogName(event.getEventType().name());
      req.setLogMsg(event.getMessage());
      req.setProxyIp(event.getProxyIp());
      req.setUserIp(event.getUserIp());
      if (null != event.getPrincipal()) {
        req.setCreateBy(UUIDUtil.fromString(event.getPrincipalName()));
      } else {
        req.setCreateBy(UUIDUtil.emptyUUID());
      }
      req.setEnvProps(metadata.getInjectionPoint().toString());
      userLogWrite.insert(req);
    } catch (Exception ex) {
      log.error("保存安全日志错误:", ex);
    } finally {
      RbacFactory.destroy(userLogWrite);
    }
  }


}
